import logging
import os
from datetime import datetime


class Logger:
    """日志记录类"""
    _instance = None
    _logger = None

    def __new__(cls, log_file=None, log_level=logging.INFO):
        if not cls._instance:
            cls._instance = super().__new__(cls)
            cls._instance._init_logger(log_file, log_level)
        return cls._instance

    def _init_logger(self, log_file, log_level):
        # 创建logger
        self._logger = logging.getLogger('api_test')
        self._logger.setLevel(log_level)

        # 设置日志格式
        formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')

        # 创建控制台处理器
        ch = logging.StreamHandler()
        ch.setLevel(log_level)
        ch.setFormatter(formatter)
        self._logger.addHandler(ch)

        # 创建文件处理器（如果指定了日志文件）
        if log_file:
            # 确保日志目录存在
            log_dir = os.path.dirname(log_file)
            if not os.path.exists(log_dir):
                os.makedirs(log_dir)

            fh = logging.FileHandler(log_file, encoding='utf-8')
            fh.setLevel(log_level)
            fh.setFormatter(formatter)
            self._logger.addHandler(fh)

    @classmethod
    def get_logger(cls):
        """获取日志实例"""
        # 从配置文件获取日志设置
        from utils.config_parser import ConfigParser
        config = ConfigParser.get_config()

        log_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), '../logs')
        if not os.path.exists(log_dir):
            os.makedirs(log_dir)

        log_file = os.path.join(log_dir, f'test_{datetime.now().strftime("%Y%m%d")}.log')
        log_level = getattr(logging, config.get('logging', 'level', fallback='INFO').upper())

        return cls(log_file, log_level)._logger
